package cn.deschen.eshop.auth.validate.sms;

import cn.deschen.eshop.auth.enums.ValidateCodeTypeEnum;
import cn.deschen.eshop.auth.properties.SecurityProperties;
import cn.deschen.eshop.auth.properties.SmsCodeProperties;
import cn.deschen.eshop.auth.validate.ValidateCode;
import cn.deschen.eshop.auth.validate.ValidateCodeGenerator;
import cn.deschen.eshop.auth.validate.image.ImageValidateCodeGenerator;
import cn.deschen.eshop.common.enums.GlobalEnum;
import cn.deschen.eshop.common.exception.GlobalException;
import cn.deschen.eshop.common.utils.HttpUtils;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @Author hanbin_chen
 * @Description 手机验证码生成器
 * @DateTime 2021/1/15 16:02
 * @Version V1.0.0
 */
@Slf4j
@Component
@ConditionalOnClass(value = SmsValidateCodeGenerator.class)
public class SmsValidateCodeGenerator implements ValidateCodeGenerator {

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public ValidateCode generate(ServletWebRequest request) {
        return new SmsValidateCode(getCode(securityProperties.getCode().getSms().getLength()));
    }

    public static String getCode(String length) {
        // 范围 10的(length-1)次方到9*10的(length-1)次方
        Double dCode = (Math.random() * 9 + 1) * Math.pow(10, Integer.parseInt(length) - 1);
        return String.valueOf(dCode.intValue());
    }
}
